# Title     : TODO
# Objective : TODO
# Created by: xuyj
# Created on: 2020/10/14 0014
pacman::p_load(dplyr, magrittr, lazyopt, sqldf)
opt <- matrix(c("firstinputfile", "i1", 2, "character", "first inputfile path", "",
                "secondinputfile", "i2", 2, "character", "second inputfilepath", "",
                "outputfile", "o", 2, "character", "output file path", "",
                "checkLine", "cl", 2, "character", "Set those two columns for comparison", "",
                "connecttype", "ct", 1, "character", "left ,right ,in", "right"
), ncol = 6, byrow = TRUE) %>% lazyopt()
firstData <- read.delim(opt$firstinputfile, check.names = FALSE, header = TRUE)
secondData <- read.delim(opt$secondinputfile, check.names = FALSE, header = TRUE)

lines <- opt %$% lazyopt::fenge(checkLine) %>% as.numeric()
a <- (firstData %>% colnames())[lines[1]]
b <- (secondData %>% colnames())[lines[2]]
type <- match.arg(opt$connecttype, c("left", "right", "in"))
sqlstring <- NULL
if (type == "in") {
  sqlstring <- "select *from firstData a,secondData b where " %>% paste0(., "a.", a, "=b.", b)
}
if (type == "left") {
  sqlstring <- "select *from firstData a left join secondData b on " %>% paste0(., "a.", a, "=b.", b)
}
if (type == "right") {
  sqlstring <- "select *from secondData b left join firstData a on " %>% paste0(., "a.", a, "=b.", b)
}
result <- sqldf(sqlstring)
result[is.na(result)] <- ""
write.table(result, file = opt$outputfile, sep = "\t", row.names = FALSE)






